<template>
    <div 
        class="page-x"
        @click.stop="clickEvent($event)"
        @touchstart.stop ='moveStart($event)'
        @touchmove.stop ='moving($event)'
        @touchend.stop ='moveEnd($event)'>

        <!-- 点击中间1/3后弹出的菜单 -->
        <div 
            class="menu" 
            v-show="isClick"
            @click.stop.self="closeMenu"
            @touchstart.stop =''
            @touchmove.stop =''
            @touchend.stop =''>
            <div class="menu-top">
                <div class="goback" @click="goback()">
                    <i class="iconfont icon-fanhui"></i> 返回
                </div>
                <div class="home" @click="gohome()">返回首页</div>
            </div>
            <div class="menu-mid">
                <div 
                    class="menu-mid-l"
                    @click="goUp">
                    <div class="text">
                        上一章
                    </div>
                </div>
                <div 
                    class="menu-mid-r"
                    @click="goDown">
                    <div class="text">
                        下一章
                    </div>
                </div>
            </div>
            <div class="menu-bottom">
                <div 
                    class="content"
                    @click="gotoChater(bid)">
                    目录
                </div>
                <div 
                    class="bg"
                    @click.self="showBgMenu()">
                    背景
                    <div 
                        class="bg-menu"
                        v-show="isBackground">
                        <div 
                            v-for="item,index in $store.state.user.bgs"
                            :key="index"
                            :style="{'background-image': `url(${$store.state.user.bgs[index]})`,}"
                            :class="{'bg-item':true,active:$store.state.user.bgn == index}"
                            @click="setBg(index)">
                        </div>
                    </div>
                </div>
                <div 
                    class="font-size"
                    @click.self="showFontMenu()">
                    字号
                    <div 
                        class="font-menu"
                        v-show="isFontSize">
                        <div class="add" @click="changeFontSize(1)">
                            <i class="iconfont icon-font"></i>+
                        </div>
                        <div class="sub" @click="changeFontSize(-1)">
                            <i class="iconfont icon-font"></i>-
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        
        <!-- 这是移动端的左右滑动组件 -->
        <div 
            class="photos"
            ref="pageEle"
            :style="{'font-size':$store.state.user.fSize+'px !important',
                        color:$store.state.user.fColor[$store.state.user.bgn]}">
            <slot></slot>
            <span class="bottom" ref="bottom"></span>
        </div>
        <div 
            class="page-index"
            :style="{color:$store.state.user.fColor[$store.state.user.bgn]}">
            {{readPre}}%
        </div>
    </div>

</template>

<script>
export default {
    name: 'pageX',
    props: {
        pageWidth: Number,
        gapWidth: Number,
        bid: String
    },
    data() {
        return {
            nowX: 0, // 元素的水平位置
            newX: 0, // 移动时的新水平位置
            startX: 0, // 移动开始的坐标
            startY: 0,
            moveX: 0, // 移动中的坐标
            moveY: 0, 
            distanceX: 0, // 移动的相对坐标
            distanceY: 0, 
            endX: 0, // 移动结束的坐标
            endY: 0,
            isMoving: false,
            active_dis : 5, // 移动超过10px，表示移动此方向
            isWASD : -1, // -1表示不确定方向 0：上 1：右 2：下 3：左 
            pageIndex: 0,
            touchSpeed: 1.2, // 元素移动速度相对手指的移动速度的倍率
            animateMoving: false, // 动画正在实现
            timer: null, // 动画计时器
            fSize: 18,
            readPre: 0,
            isClick: false, // 总菜单
            isFontSize: false, // 设置字体菜单
            isBackground: false, // 设置背景菜单
        }
    },
    methods: {
        // 移动开始
        moveStart(e) {
            this.liftDefault();
            this.stopDefault();
            // 若动画正在移动，就直接退出函数
            if(this.animateMoving) {
                return;
            }
            // console.log('开始移动','x',e.targetTouches[0].pageX,'y',e.targetTouches[0].pageY);
            this.startX = e.targetTouches[0].pageX;
            this.startY = e.targetTouches[0].pageY;
            this.isMoving = true;
        },
        // 正在移动
        moving(e) {
            // 若动画正在移动，就直接退出函数
            if(this.animateMoving) {
                return;
            }
            // console.log('正在移动',this.isMoving);
            // console.log(e);
            this.moveX = e.changedTouches[0].pageX;
            this.moveY = e.changedTouches[0].pageY;
            // console.log('正在移动','x',this.moveX,'y',this.moveY);
            // console.log('正在移动',this.isWASD);
            this.distanceX = this.moveX - this.startX;
            this.distanceY = this.moveY - this.startY;
            // 移动方向还没确定
            if(this.isWASD == -1){
                // 左
                if(this.distanceX <= -0.5*this.active_dis){
                    this.isWASD = 3;
                }
                // 右
                else if(this.distanceX >= 0.5*this.active_dis){
                    this.isWASD = 1;
                }
            }
            // 若确定左右移动
            if(this.isWASD == 3){
                this.newX = this.nowX + this.distanceX *this.touchSpeed;
                if(this.newX < 0 && Math.abs(this.newX) >= this.$refs.bottom.offsetLeft + this.pageWidth/4 ){
                    this.newX = -(this.$refs.bottom.offsetLeft +this.pageWidth/4)
                }
                if(this.newX >= this.pageWidth /4){
                    this.newX = this.pageWidth /4;
                }
                // 跟着手指移动
                this.setX(this.newX);
            }
            if(this.isWASD == 1){
                this.newX = this.nowX + this.distanceX *this.touchSpeed;
                if(this.newX < 0 && Math.abs(this.newX) >= this.$refs.bottom.offsetLeft + this.pageWidth/4 ){
                    this.newX = -(this.$refs.bottom.offsetLeft +this.pageWidth/4)
                }
                if(this.newX >= this.pageWidth /4){
                    this.newX = this.pageWidth /4;
                }
                // 跟着手指移动
                this.setX(this.newX);
            }
            // console.log('page this.nowX',this.nowX);
        },
        // 移动结束
        moveEnd(e) {
            // 若动画正在移动，就直接退出函数
            if(this.animateMoving || !this.isMoving) {
                this.isWASD = -1;
                this.isMove = false;
                return;
            }
            // console.log('结束移动', this.animateMoving, this.isMoving, 
                        // 'this.nowX',this.nowX,'this.newX',this.newX);
            this.endX = e.changedTouches[0].pageX;
            this.endY = e.changedTouches[0].pageY;
            this.animateMoving = true; // 动画正在移动

            // 若确定左右移动, 则开始移动元素
            if(this.isWASD == 3){
                // 更新现在的元素位置
                this.nowX = this.newX;
                for(let i =0;i<2000;i++){
                    if(this.nowX > - i* this.pageWidth - this.pageWidth / 2){
                        this.newX = - i* this.pageWidth;
                        this.pageIndex = i;
                        break;
                    }
                }
            }
            if(this.isWASD == 1){
                // 更新现在的元素位置
                this.nowX = this.newX;
                for(let i =0;i<2000;i++){
                    if(this.nowX > - i* this.pageWidth - this.pageWidth / 2){
                        this.newX = - i* this.pageWidth;
                        this.pageIndex = i;
                        break;
                    }
                }
            }
            // console.log('page this.nowX',this.nowX);
            // console.log('page this.pageNum',this.pageNum);
            // console.log('page this.pageWidth',this.pageWidth);
            // console.log('page this.newX',this.newX);

            // 开始移动动画
            this.animateDoing(this.newX);
            // 移动结束重置状态

            // console.log('this.pageIndex',this.pageIndex);
            this.isWASD = -1;
            this.isMoving = false;
        },
        // 禁止页面上下滚动
        // 禁止的函数
        preventDef(e) {
            e.preventDefault()
        },
        stopDefault() {
            // console.log('锁定');
            document.body.addEventListener('touchstart', this.preventDef, {passive: false})
            document.body.addEventListener('touchmove', this.preventDef, {passive: false})
        },
        // 解禁页面上下滚动
        liftDefault() {
            // console.log('解除');
            document.body.removeEventListener('touchstart', this.preventDef)
            document.body.removeEventListener('touchmove', this.preventDef)
        },
        animateDoing(position) {
            if(this.timer != null) {
                return;
            }
            this.timer = setInterval(()=>{
                let step = (position - this.nowX)/5;
                step = step < 0 ? Math.floor(step) : Math.ceil(step);
                this.nowX = this.nowX + step;
                if(Math.abs(this.nowX - position) <= 5){
                    this.nowX = position;
                    this.setX();
                    this.animateMoving = false;
                    this.liftDefault();
                    this.updatePre();
                    clearInterval(this.timer);
                    this.timer = null;
                    return ;
                }
                this.setX();
            },1)
        },
        // 设置父盒子的偏移量
        setX(newX) {
            if(newX == undefined){
                newX = this.nowX;
            }
            // console.log('this.$refs',this.$refs.pageEle);
            if(this.$refs.pageEle == undefined){
                return;
            }
            // console.log('this.$refs.pageEle',this.$refs.pageEle.style);
            this.$refs.pageEle.style.transform= 'translateX('+ newX +'px)';
            
        },
        // 移动至此下标
        gotoIndex(i) {
            this.newX = - i* this.pageWidth;
            this.pageIndex = i;
            // 开始移动动画
            // console.log('goto index',this.newX);
            this.animateDoing(this.newX);
        },
        // 更新读书进度
        updatePre() {
            let no_read = this.$refs.bottom.offsetLeft + this.nowX;
            if(no_read < this.pageWidth /1.2 || this.$refs.bottom.offsetLeft == 0){
                no_read = 100;
            }else {
                no_read = Math.floor((-this.nowX) / this.$refs.bottom.offsetLeft *100);
            }
            this.readPre = no_read;
        },
        clickEvent(e) {
            // console.log('click gogogo');
            this.isClick = !this.isClick;
        },
        printS(str){
            console.log(str);
        },
        //返回上一级
        goback(){
            this.$router.go(-1);
        },

        // 返回首页
        gohome(){
            this.$router.push('/')
        },
        // 关闭菜单
        closeMenu() {
            if(this.isFontSize){
                this.isFontSize = false;
            }
            else if(this.isBackground){
                this.isBackground = false;
            }else if(this.isClick) {
                this.isClick = false;
            }
        },
        changeFontSize(sign){
            let i = this.$store.state.user.fSize;
            if(sign >0){
                i += 2;
            }
            else {
                i -= 2;
            }
            // console.log('font change');
            this.$store.commit('user/setFontSize',i);
            setTimeout(() => {
                this.updatePre();
                // 若字体变小，超出最后一页，则回到最后一页
                for(let i =0;i<2000;i++){
                    if(this.newX < 0 && Math.abs(this.newX) >= this.$refs.bottom.offsetLeft + this.pageWidth/4 ){
                        this.newX = - this.$refs.bottom.offsetLeft;
                        break;
                    }
                    if(this.nowX > - i* this.pageWidth - this.pageWidth / 2){
                        this.newX = - i* this.pageWidth;
                        this.pageIndex = i;
                        break;
                    }
                }
                // 开始移动动画
                this.animateDoing(this.newX);
            }, 2);
        },
        // 显示或隐藏字体菜单
        showFontMenu() {
            // console.log('font clicks');
            if(this.isFontSize) {
                this.isFontSize = false;
            } else {
                this.isBackground = false;
                this.isFontSize = true;
            }
        },
        // 显示或隐藏背景菜单
        showBgMenu() {
            if(this.isBackground) {
                this.isBackground = false;
            } else {
                this.isBackground = true;
                this.isFontSize = false;
            }
        },
        // 改变背景
        setBg(i) {
            this.$store.commit('user/setBgn',i);
        },
        // 回到目录页
        gotoChater(id) {
            this.$router.push('/book-chater/'+id+'/m');
        },
        // 上一章
        goUp() {
            this.$emit('chaterSub');
        },
        // 下一章
        goDown() {
            this.$emit('chaterAdd');
        }
    },
    mounted() {
        // console.log(this.$refs.bottom.offsetLeft);
    }
}
</script>

<style lang="scss" scoped>
@import '@/assets/common/variable.scss';
.page-x {
    // position: relative;
    height: 100%;
    .page-index {
        // position: absolute;
        // bottom: 0px;
        font-size: 12px;
        line-height: 16px;
        text-align: right;
        // right: 0px;
    }
    .menu {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba($color: #000000, $alpha: 0.4);
        z-index: 999999;
        font-size: 16px;
        .menu-bottom,
        .menu-top {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 50px;
            background-color: white;
            display: flex;
            padding: 0 20px;
            justify-content: space-between;
            box-sizing: border-box;
            line-height: 50px;
            & > div {
                padding: 0 10px;
            }
        }
        .menu-top {
            top: 0;
        }
        .menu-mid-r,
        .menu-mid-l {
            width: 100px;
            height: 100px;
            
            border-radius: 50%;
            position: absolute;
            top: 50%;
            margin-top: -50px;
            right: -50px;
            background-color: white;
            writing-mode:vertical-lr;
            .text {
                width: 50px;
                line-height: 50px;
                text-align: center;
            }
        }
        .menu-mid-l{
            left: -50px;
            .text {
                margin-left: 50px;
            }
        }
        .bg-menu,
        .font-menu {
            position: absolute;
            height: 50px;
            top: -50px;
            left: 0;
            width: 100%;
            background-color: white;
            display: flex;
            justify-content: space-around;
            align-items: center;
            font-size: 18px;
            font-family: oppo-l;
            padding: 10px;
            box-sizing: border-box;
            & >div {
                flex: 1;
                height: 40px;
                line-height: 40px;
                text-align: center;
                background-color: #ddd;
                border-radius: 6px;
                margin-right: 10px;
                box-sizing: border-box;
                &:last-child {
                    margin-right: 0px; 
                }
            }
        }
        .bg-menu {
            .bg-item {
                border: 4px solid transparent;
            }
            .active {
                border: 4px solid rgb(96, 150, 26);
            }
        }
    }
    & /deep/ h1 {
        font-size: 26px;
        text-align: center;
    }
    & /deep/ img {
        width: 335px;
        object-fit: contain;
    } 
}
.photos {
    height: calc(100% - 16px);
    columns: calc(100vw - 40px) 1;
    column-gap: 20px;
    box-sizing: border-box;
}
.bottom {
    width: 0px;
    height: 0px;
    margin: 0;
    padding: 0;
}

</style>